<?php
require_once("../../../config.inc.php");
$isReloadable = false;
require_once("../../../app/_inc/include.php");
require_once("./_inc/entpFunction.php");

$errMsg = "";
$process_unit = sxREQ('pu');
if($process_unit == ""){	
	$url = $_SESSION[USEROBJ]->getHistory(0, true).
		"&msg=".urlencode(_t("missing cod. 'pu'"));
	serverRedir($url);
}
$entry_point = sxREQ('ep');
if($entry_point == ""){	
	$url = $_SESSION[USEROBJ]->getHistory(0, true).
		"&msg=".urlencode(_t("missing cod. 'ep'"));
	serverRedir($url);
}
$name = sxREQ('name');
if($entry_point == ""){	
	$url = $_SESSION[USEROBJ]->getHistory(0, true).
		"&msg=".urlencode(_t("missing cod. 'name'"));
	serverRedir($url);
}

if(sxREQ("reqtype") == "save"){
	$errMsg .= entpruleIns();
}
$sSQL = "SELECT * FROM entry_point_rule "
	." WHERE process_unit = '$process_unit' AND entry_point = '$entry_point' "
		." AND name = '$name'";
$objSDAO->query($sSQL, "comRule");
if (!$row = $objSDAO->fetch("comRule")){
	$url = $_SESSION[USEROBJ]->getHistory(0, true).
		"&msg=".urlencode("missing rule '$process_unit/$entry_point/$name'");
	serverRedir($url);
}

sxRDef('new_name', $row['name']);
sxRDef('description', $row['description']);
sxRDef('sequence', $row['sequence']);
sxRDef('com_rule', $row['module'].'.'.$row['com_rule_name']);
sxRDef('note', $row['note']);
sxRDef('script', $row['script']);
sxRDef('upgrade_status', $row['upgrade_status']);
sxRDef('is_sub', $row['is_sub']);

$sSQL = "SELECT * FROM com_rule ORDER BY module, name";
$objSDAO->query($sSQL, "comRule");
$aComRule = array('.'=>'-- select --');
while($row = $objSDAO->fetch("comRule")){
	$aComRule[$row["module"].$row["name"]] == $row["module"].$row["module"].' - '.$row["description"];
}

$aOpz = array("kMenu"=>'pro.pru', "isReloadable"=>$isReloadable);
echo(headerHTML($aOpz));
?>
<script language="JavaScript" type="text/javascript">
function objFrmSubm(rt){
	document.objFrm.reqtype.value = rt;
	document.objFrm.submit();
}
</script>
  
<?php
echo(bodyHTML($aOpz));

echo getEntpHeader($process_unit,$entry_point);

$aCmd = array("save"=>array("pag"=>"javascript:objFrmSubm('save')",
										"title"=>_t("save"),
										"text"=>_t("save")
										),
					"back"=>array()
					);
$sCmd = commandsHTML($aCmd);	
echo $sCmd;

echo getHtmlForm('objFrm');
echo getHtmlHidden('xsn',XSN);
echo getHtmlHidden('reqtype','...');
echo getHtmlHidden('pu');
echo getHtmlHidden('ep');
echo getHtmlHidden('name');

echo("<table class=\"tabl01\" width=\"100%\" cellpadding=\"3\" cellspacing=\"2\" border='0'>\n");
echo("<tr>" .
			"<td class=\"titl01\" colspan='3'>Rule</td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\" width=\"20%\">Name*</td>" .
			"<td class=\"text01\" width=\"80%\" colspan='2'>".getHtmlText('new_name',32,32)."</td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">Description*</td>" .
			"<td class=\"text01\" colspan='2'>".getHtmlText('description',80,80)."</td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">Sequence*</td>" .
			"<td class=\"text01\" colspan='2'>".getHtmlText('sequence',4,4)."</td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">Common rule</td>" .
			"<td class=\"text01\" colspan='2'>".getHtmlSelect('com_rule',$aComRule)."</td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">Is a subroutine</td>" .
			"<td class=\"text01\" colspan='2'>".getHTMLRadio('is_sub', array('N'=>'no','Y'=>'yes'))."</td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">Upgrade status</td>" .
			"<td class=\"text01\" colspan='2'>".getHTMLRadio('upgrade_status', getUpgradeStatusVal())."</td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">Note</td>" .
			"<td class=\"text01\" colspan='2'>".getHtmlTextArea('note',80,2)."</td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">Script*<br><br>" .
			getHtmlCheckBox('reformat', 'Y')." re-format");		
//parameters for entry-point
$sSQL = "SELECT * FROM entry_point_variable WHERE process_unit='$process_unit' AND entry_point='$entry_point'";
$objSDAO->exec($sSQL, "epv");
if($row = $objSDAO->fetch("epv")){
	echo ("<br><br>Parameters:<br>");
}
while($row){
	echo($row["variable"]."<br>");
	$row = $objSDAO->fetch("epv");
}
//avialable attribute and memory var
$aVarAbil = getVarAbil($process_unit, $entry_point);
echo("<td class=\"text01\">" 
			.getHtmlTextAreaScript('script',70,20)
			."</td><td class=\"text01\" valign='top'>" .implode(', ',array_keys($aVarAbil))
			."</td></tr>\n");
echo("</table>");
echo $sCmd;
echo("</form>");
echo("</td>\n</tr>\n</table>\n");
echo(footerHTML());
exit();

function entpRuleIns($redirOnEnd = true){
	global $objSDAO;
	$errMsg = "";
	if(sxRTrim("pu") == '')
		$errMsg .= "missing process-unit<br>";
	if(sxRTrim("ep") == '')
		$errMsg .= "missing entry-point<br>";
	if(sxRTrim("name") == '')
		$errMsg .= "missing name old<br>";
	if(sxRTrim("new_name") == '')
		$errMsg .= "missing name<br>";
	if(preg_match("/[^a-zA-Z0-9_]/",sxREQ("new_name")))
		$errMsg .= "name: only letter, nummber and _ allowed<br>";
	if(preg_match("/[^0-9]/",sxREQ("sequence")))
		$errMsg .= "sequence not numeric<br>";
	if(sxRTrim("description") == '')
		$errMsg .= "missing description<br>";
	//existence
	if (sxREQ("new_name")!=sxREQ("name"))
	$sSQL = "SELECT name FROM entry_point_rule "
		." WHERE name='".sxRAS("new_name")."'" .
			" AND entry_point='".sxRAS("ep")."'" .
			" AND process_unit='".sxRAS("pu")."'";
	$objSDAO->query($sSQL,"test");
	if($row)
		$errMsg .= "existing name<br>";
		
	//check script
	$script = sxRTrim("script");
	$objParse = new polarisParser;
	if(!$objParse->parse($script)) {
		return $objParse->getError();
	}
	$aVarAbil = getVarAbil(sxREQ("pu"), sxREQ("ep"));
	//dbg_("aVarAbil: ".print_r($aVarAbil,1));
	//dbg_("objParse->aVariables: ".print_r($objParse->aVariables,1));
	foreach($objParse->aVariables as $varName => $aPropVar) {
		if (strpos('TRS_',$varName[0])!== false) { // temporary or system variable
			continue;
		}
		if (!isset($aVarAbil[$varName])) {
			$errMsg .= _t("variable '%s' not available",$varName)."<br>";
			continue;
		}
		if ($aPropVar['modified'] and $aVarAbil[$varName] == 'Y') {
			$errMsg .= _t("variable '%s' read-only",$varName)."<br>";
		}
	}

	$aFunzDisp = getFunzDisp(sxREQ("pu"));
	foreach($objParse->aFunctions as $funzName => $aFunzVar) {
		if (!isset($aFunzDisp[$funzName])) {
			$errMsg .= _t("function '%s' not available",$funzName)."<br>";
			continue;
		}
		if ($aFunzVar['numPar'] !=  count($aFunzDisp[$funzName])) {
			$errMsg .= _t("function '%s' with %s parameters - required %s",
				$funzName,$aFunzVar['numPar'],count($aFunzDisp[$funzName]))."<br>";
		}
	}
		
	if($errMsg != "") {
		return $errMsg;
	}	
	if (sxREQ('reformat')=='Y') {
		$script = $objParse->getFormatCode();
	}
	
	$aModComR = explode('.',sxREQ('com_rule'));
	$sSQL = "UPDATE entry_point_rule SET module = '".sxAS(sxVx($aModComR,0))."' " .
			",com_rule_name = '".sxAS(sxVx($aModComR,1))."'" .
			",sequence = ".sxRInt("sequence") .
			",description = '".sxRAS("description")."'" .
			",note = '".sxRAS("note")."'" .
			",script = '".sxAS($script)."'" .
			",upgrade_status = '".sxRAS("is_sub")."'" .
			",is_sub = '".sxRAS("upgrade_status")."'" .
			" WHERE name='".sxRAS("name")."'" .
			" AND entry_point='".sxRAS("ep")."'" .
			" AND process_unit='".sxRAS("pu")."'";
	$objSDAO->exec($sSQL);
	$url = $_SESSION[USEROBJ]->getHistory(0, true);
	serverRedir($url);
	return 'redir err';
}
